<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\common\controller\Api;
use app\common\model\VideoOrder;
use app\common\model\VipOrder;

/**
 * 支付回调接口
 */
class Pay extends Api
{


    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 支付回调
     */
    public function notify()
    {
        $paytype = $this->request->param('paytype');
        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            return json(['code' => 'FAIL', 'message' => '失败'], 500, ['Content-Type' => 'application/json']);
        }
        // 获取回调数据，V3和V2的回调接收不同
        $data = Service::isVersionV3() ? $pay->callback() : $pay->verify();
        try {
            //微信支付V3返回和V2不同
            if (Service::isVersionV3() && $paytype === 'wechat') {
                $data = $data['resource']['ciphertext'];
                $data['total_fee'] = $data['amount']['total'];
            }
            //获取支付金额、订单号
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            //回调订单编号
            $pay_sn = $paytype == 'alipay' ? $data['trade_no'] : $data['transaction_id'];
            # 订单号
            $out_trade_no = $data['out_trade_no'];
            $prefix = explode('_', $out_trade_no)[0] ?? '';
            switch ($prefix) {
                case 'VIP':  # 开通vip
                    $vipOrder = (new VipOrder());
                    $vipOrder->notify_order($out_trade_no, $pay_sn, $payamount);
                    break;
                case 'VIDEO':  # 购买视频课
                    $videoOrder = (new VideoOrder());
                    $videoOrder->notify_order($out_trade_no, $pay_sn, $payamount);
                    break;
                default:
                    break;
            }
            \think\Log::record("回调成功，订单号：{$out_trade_no}，金额：{$payamount}");
            //你可以在此编写订单逻辑
        } catch (\Exception $e) {
            \think\Log::record("回调逻辑处理错误:" . $e->getMessage(), "error");
        }
        //下面这句必须要执行,且在此之前不能有任何输出
        if (Service::isVersionV3()) {
            return $pay->success()->getBody()->getContents();
        } else {
            return $pay->success()->send();
        }
    }
}
